import os

from models.asyncExecLogModel import AsyncDownloadLogModel
from models.baseModel import get_session


class DownloadLog:
    def __init__(self, id):
        super(DownloadLog, self).__init__()
        self._id = id

    """
    创建日志
    """
    def add_log(self, type, file_path, start_time):
        file_name = os.path.basename(file_path)

        session = get_session()

        async_download_log = AsyncDownloadLogModel()
        async_download_log.version_id = self._id
        async_download_log.type = type
        async_download_log.file = file_path
        async_download_log.file_name = file_name
        async_download_log.start_time = start_time
        async_download_log.status = 0

        session.add(async_download_log)

        # 提交
        session.commit()
        # 获取ID
        log_id = async_download_log.id
        # 关闭
        session.close()
        return log_id

    """
    更新日志
    """
    def update_log(self, log_id, end_time, status, reason=None):
        session = get_session()

        params = {
            'end_time': end_time,
            'status': status,
            'reason': reason
        }
        session.query(AsyncDownloadLogModel).filter(AsyncDownloadLogModel.id == log_id).update(params)

        # 提交&关闭
        session.commit()
        session.close()